﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Hp.Vertica.Client.Internal;

namespace Hp.Vertica.Client
{
    /// <summary>
    /// Interaction logic for SqlConnection.xaml
    /// </summary>
    public partial class SqlConnection : Window
    {
        public event EventHandler Saved;

        public void Save(Object state)
        {
            if (Saved != null)
            {
                Saved.Invoke(state, null);
            }
            this.Close();
        }

        public SqlConnection()
        {
            InitializeComponent();
            if (ViewModel == null)
            {
                ViewModel = new SqlConnectionViewModel();
                ViewModel.DataSource = "16.186.76.37";
                ViewModel.IntegratedSecurity = false;
                ViewModel.User = "sa";
                ViewModel.Password = "sa1qaz!QAZ";
            }
        }

        public SqlConnection(SqlConnectionViewModel model)
            : base()
        {
            this.ViewModel = model;
        }

        private CancellationTokenSource tokenSource = new CancellationTokenSource();
        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            SqlConnectionViewModel vm = this.ViewModel;
            var temp = tokenSource = new CancellationTokenSource();//captured variable
            this.ViewModel.IsConnecting = true;
            Task.Factory.StartNew((c) =>
            {
                try
                {
                    var model = vm.Save();
                    if (temp.Token.IsCancellationRequested) { return; }
                    this.Dispatcher.Invoke(() =>
                    {
                        this.Save(model);
                    }, System.Windows.Threading.DispatcherPriority.Normal, (c as CancellationTokenSource).Token);
                }
                catch (Exception exc)
                {
                    if (temp.Token.IsCancellationRequested) { return; }
                    MessageBox.Show(exc.Message);
                }
                finally
                {
                    vm.IsConnecting = false;
                }
            }, temp, temp.Token);

        }

        private void ConnectCancel_Click(object sender, RoutedEventArgs e)
        {
            tokenSource.Cancel();
            this.ViewModel.IsConnecting = false;
        }

        public SqlConnectionViewModel ViewModel
        {
            get { return this.DataContext as SqlConnectionViewModel; }
            set { this.DataContext = value; }
        }

    }
}
